<template>
  <div>
    <el-table
      :header-cell-style="{background:'#f9f9ff'}"
      border
      :data="tableHistory"
      style="width: 100%;"
      max-height="350">
      <el-table-column
        fixed
        prop=""
        type="index"
        label="序号"
        width="50">
      </el-table-column>
      <el-table-column
        prop="sq"
        label="公司名称">
        <template slot-scope="scope">
          <span data-count="goHistoryBtn" class="name_link" @click.stop="goHistory(scope.$index, tableHistory, true)">{{scope.row.sq}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="insertDate"
        width="180px"
        label="浏览时间">
      </el-table-column>
    </el-table>
    <vPagination :total="total" :ips="pageSize" @currentPage="getCurrentPage"/>
    <!-- 数据进度 -->
    <el-dialog
      title="数据生成进度"
      :visible.sync="dialogPercent"
      :before-close="closeTypes"
      width="45%"
      append-to-body
      class="eldialog">
      <el-progress class='elprogress' :percentage="percent"></el-progress>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeTypes">后台处理</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import vPagination from './vPagination'
let types = null
export default {
  inject: ['reload'],
  props: ['dialogHistory'],
  components: {
    vPagination
  },
  data() {
    return {
      tableHistory: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      dialogPercent: false,
      percent: 0,
      cancel: null,
      eid:''
    }
  },
  methods: {
    // 获取浏览历史列表
    getHistory(){
      this.tableHistory = [];
      this.$get(`${this.$Url.history.getHistory}/${this.currentPage}/${this.pageSize}`)
        .then(data => {
          let result = data.data.result
          result.forEach((v) => {
            let sq = JSON.parse(JSON.stringify(v.sq))
            try {
              v.sq = JSON.parse(sq).companyName
              v.eid = JSON.parse(sq).eid
            } catch (error) {}
          })
          
          this.tableHistory = result
          this.total = data.data.total
        }).catch(error => {
        console.log(error);
      })
    },
    // 跳转浏览历史
    goHistory(index, row, isNeedCheck){
      let companyName = row[index].sq.split('_eid_')[0]
      let eid = row[index].eid || ''
      localStorage.setItem("eid",eid) // 2020 04 13 zjs save
      if(companyName.indexOf('xxxx')>-1){
        this.$message({
          type: 'error',
          message: '当前账号暂无权限访问！'
        })
        return
      }

      types = null
      let checkUrl = this.$Url.search.check
      if(!isNeedCheck){
        checkUrl = this.$Url.search.check2
      }
      let ths = this
      this.$get(checkUrl, {
        companyName: companyName,
        eid: eid
      }, new axios.CancelToken(function executor(c) {
        ths.cancel = c
      })).then(res => {
        // 无访问权限
        if(res.status === 40305){
          return
        }
        // 默认重置公司是否有专利的cookie
        this.$cookie.set('isHavePatent', true)
        // 清除公司国别的cookie
        this.$cookie.remove('companyCountry')

        let promise = new Promise((resolve, reject) => {
          // 获取公司国别
          this.$get(this.$Url.company.country, {
            eid: eid
          }).then(data => {
            this.$cookie.set('companyCountry', data.data)
            resolve('next')
          })
        })
        promise.then(() => {
          // 获取新闻信息
          this.$post(this.$Url.news.getData, {
            name: companyName
          }).then(data => {}).catch(e=>{console.log(e);})

          if(res.status === 40401){
            this.$cookie.set("companyName", companyName)
            this.$cookie.set('isHavePatent', false)
            this.addHistory(companyName, eid)
            this.$router.push({
              name: 'science'
            })
            this.reload()
            return
          }

          if(res.data&&res.data.type == 0){
            this.$cookie.set("companyName", companyName)
            this.addHistory(companyName, eid)
            this.$router.push({
              name: 'science'
            })
            if(types != null){
              clearTimeout(types)
              types = null;
            }
            this.reload()
          }
          if(res.data.type == 1){
            this.$confirm('暂无数据，后台生成数据需要一定的时间', '是否继续？', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.$get(this.$Url.search.generateData, {
                companyname: companyName,
                jueduidefen: true,
                eid: eid
              }).then(res => {
                if(res.status == 205){
                  this.$message.warning(res.message)
                }
              });
            })

          }
          if(res.data.type == 2 ){
            this.dialogPercent = true;
            this.percent =  Number(res.data.percent)||0;
            types = setTimeout(() => {
              this.goHistory(index, row, false)
            },4000)
          }
          if(res.data.type == 3 ){
            this.closeTypes();
            this.$message.error('数据计算失败，请联系后台管理员')
          }
        })
      });
    },
    closeTypes(){
      this.dialogPercent = false
      clearTimeout(types)
      types = null
      // 中止请求
      this.cancel()
      this.dialogPercent = false
    },
    // 添加浏览历史
    addHistory(companyName, eid) {
      let obj = {
        companyName: companyName,
        eid: eid
      }
      this.$post(this.$Url.history.addHistory,{
        sq: JSON.stringify(obj)
      }).then(res => {}).catch(err => {});
    },
    // 分页
    getCurrentPage(val) {
      this.currentPage = val
      this.getHistory()
    }
  },
  watch: {
    dialogHistory() {
      if(this.dialogHistory===true){
        this.getHistory()
      }
    }
  }
}
</script>
<style lang="scss">
.el-message-box{
  .el-button--primary {
    color: #FFF;
    background-color: $mainColor !important;
    border-color: $mainColor !important;
}
.el-button--primary:active,.el-button--primary:focus,.el-button--primary:hover{
  color: #FFF !important;
    background-color: $mainColor !important;
    border-color: $mainColor !important;
}
.el-button:focus, .el-button:hover {
    color: $mainColor;
    border-color: $mainColor;
    background-color: $hoverColor;
}
}
</style>
<style scoped>
.name_link:hover{
  text-decoration: underline;
  color:#0000ee;
  cursor: pointer;
}
</style>
